package ccm.component.input;

import ccm.common.CCMConfigManager;
import ccm.common.ReceiveDataEvent;
import ccm.common.ReceiveDataListener;
import ccm.component.override.JCheckBox;
import ccm.component.override.JSpinner;

import javax.swing.*;
import java.awt.*;
import java.util.ArrayList;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

public class InputTestJPanel extends JPanel implements ReceiveDataListener
{
    protected final ArrayList<ReceiveDataListener> receiveDataListener;
    protected final JCheckBox jCheckBox;
    protected final JSpinner jSpinner;
    protected int j=0;

    public InputTestJPanel()
    {
        super();
        setLayout(new FlowLayout());
        jCheckBox=new JCheckBox("发送");
        add(jCheckBox);
        jSpinner=new JSpinner(new SpinnerNumberModel(CCMConfigManager.setIntegerIfAbsent("ccm/component/input/InputTestJPanel/jSpinner",1),0,8192,1));
        add(jSpinner);
        jSpinner.addChangeListener((x)->{
            CCMConfigManager.setInteger("ccm/component/input/InputTestJPanel/jSpinner",(Integer)jSpinner.getValue());
        });
        receiveDataListener=new ArrayList<>();
        Executors.newSingleThreadScheduledExecutor().scheduleAtFixedRate(()->{
            if(jCheckBox.isSelected())
            {
                final int n=(Integer)jSpinner.getValue();
                byte[] tmp=new byte[n];
                for(int i=0;i<n;++i)
                {
                    ++j;
                    tmp[i]=(byte)(j&255);
                }
                final ReceiveDataEvent event=new ReceiveDataEvent(InputTestJPanel.this,tmp);
                receiveDataListener.forEach(r->
                {
                    try
                    {
                        r.receiveData(event);
                    }catch(Exception ignored)
                    {
                    }
                });
            }
        },0,10,TimeUnit.MILLISECONDS);

    }

    /**
     * 添加一个接收数据监听器
     *
     * @param listener 监听器
     * @throws NullPointerException 监听器为null时抛出此异常
     */
    public void addReceiveDataListener(ReceiveDataListener listener)
    {
        if(listener==null)
        {
            return;
        }
        if(!receiveDataListener.contains(listener))
        {
            receiveDataListener.add(listener);
        }
    }

    @Override
    public void receiveData(ReceiveDataEvent event)
    {

    }
}
